<script setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue';
import { ElScrollbar, ElInput, ElButton, ElMessage } from 'element-plus';
//个人信息
import useUserInfoStore from '@/stores/userInfo';
const userInfoStore = useUserInfoStore();
const userInfo = ref({ ...userInfoStore.info })


const inputMessage = ref('');
const messages = ref([
    // { content: '你好', time: new Date(), own: false },
    // { content: '你好，请问有什么可以帮助你的吗？', time: new Date(), own: true },
]);
const socket = ref(null)
const activityName = localStorage.getItem("activityName")
const activityId = localStorage.getItem("activityId")

const formatTime = (time) => {
    return time.toLocaleTimeString();
};

const sendMessage = async() => {
    if (inputMessage.value.trim() === '') {
        ElMessage.error("无法发送空白信息！！！");
        return;
    }
    const newMessage = {
        username: userInfo.value.username,
        userAvatar: userInfo.value.photo,
        content: inputMessage.value,
        activityId: activityId,
        time: new Date(),
    };
    socket.value.send(JSON.stringify(newMessage))
    console.log(newMessage)
    // messages.value.push(newMessage);
    inputMessage.value = '';
    // 在这里，你可以添加发送消息到服务器的代码
    scrollToBottom();
};

onMounted(() => {
    // 可以在这里初始化 WebSocket 连接
    socket.value = new WebSocket('ws://' + window.location.hostname + ':5555/websocket/' + userInfo.value.username + "/" + activityId)
    socket.value.onopen = (event) => {
        console.log('WebSocket connection opened:', event);
    };

    socket.value.onmessage = (event) => {
        const message = JSON.parse(event.data);
        messages.value.push(message);
    };

    socket.value.onclose = (event) => {
        console.log('WebSocket connection closed:', event);
    };

    socket.value.onerror = (event) => {
        console.error('WebSocket error:', event);
    };
    //初始化时滚到到底部
    scrollToBottom();
});

onUnmounted(() => {
    // Close WebSocket connection when component is destroyed
    if (socket.value) {
        socket.value.close();
    }
});

// 添加一个方法来将聊天框滚动到底部
const scrollbarRef = ref(null)
const scrollToBottom = () => {
    nextTick(()=>{
        if (scrollbarRef.value) {
            const scrollbarEl = scrollbarRef.value.$el;
            const lastMessage = scrollbarEl.querySelector('.chat-message:last-child');
            if (lastMessage) {
                console.log(lastMessage)
                lastMessage.scrollIntoView({ behavior: 'smooth', block: "start", inline: "nearest" });
            }
        }
    })
};



</script>
<template>
    <div class="chat-title">
        <el-text tag="b" style="font-size: 24px;">{{ activityName }}</el-text>
        &nbsp;&nbsp;
        <el-text size="small">{{ userInfo.username }}</el-text>
    </div>
    <div class="chat-container">
        <div class="chat-messages">
            <el-scrollbar ref="scrollbarRef">
                <div v-for="(message, index) in messages" :key="index" class="chat-message"
                    :class="{ 'own-message': message.username === userInfo.username }">
                    <div class="message-content" v-if="message.username === userInfo.username"
                        style="background-color:forestgreen">
                        {{ message.content }}
                    </div>
                    <div class="message-avatar" v-else>
                        <el-avatar :size="40" :src="message.userAvatar" />
                        {{ message.username }}
                    </div>
                    <div class="message-avatar" v-if="message.username === userInfo.username">
                        <el-avatar :size="40" :src="message.userAvatar" />
                        {{ message.username }}
                    </div>
                    <div class="message-content" v-else>
                        {{ message.content }}
                    </div>
                </div>
            </el-scrollbar>
        </div>
        <div class="chat-input">
            <el-input v-model="inputMessage" placeholder="请输入消息" @keyup.enter="sendMessage"></el-input>
            <el-button type="primary" @click="sendMessage">发送</el-button>
        </div>
    </div>
</template>


<style scoped>
.chat-title {
    border-radius: 10px;
    margin-bottom: 10px;
    text-align: center;
    border: 1px solid skyblue;
    box-shadow: 8px 8px 5px skyblue;
    padding: 8px 12px;
    background-image: linear-gradient(180deg, #fff, #ddd 40%, #ccc);
}

.chat-container {
    display: flex;
    flex-direction: column;
    height: 90%;
}

.chat-messages {
    flex: 1;
    padding: 10px;
    overflow-y: auto;
}

.chat-message {
    margin-bottom: 10px;
    display: flex;
    align-items: center;
}

.own-message {
    justify-content: flex-end;
}

.message-content {
    padding: 10px;
    background-color: #f3f3f3;
    border-radius: 10px;
    max-width: 70%;
    word-wrap: break-word;
}

.message-avatar {
    font-size: 12px;
    color: #999;
    margin-left: 10px;
    text-align: center;
}

.chat-input {
    border-radius: 10px;
    display: flex;
    margin: 0 auto;
    align-items: center;
    padding: 10px;
    background-color: #f9f9f9;
    width: 65%;
}

.el-input {
    margin-right: 10px;
}
</style>